// Fetch prints the content found at a URL.
package main

import (
	"bufio"
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
)

func main() {
	for _, url := range os.Args[1:] {
		if strings.HasPrefix(url, "https://") {
		} else {
			url = "https://" + url
		}

		resp, err := http.Get(url)
		if err != nil {
			fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
			os.Exit(1)
		}
		fmt.Println("Status =", resp.Status)
		//b, err := ioutil.ReadAll(resp.Body)
		//下面用io.copy替代
		//先创建一个文件用于存储内容
		out, err := os.Create("url_content")
		if err != nil {
			fmt.Fprintf(os.Stderr, "create file failed:%v\n", err)
			os.Exit(1)
		}
		wt := bufio.NewWriter(out)
		defer out.Close()
		n, err := io.Copy(wt, resp.Body)
		io.Copy(os.Stdout, resp.Body) //os.Stdout存储的是一个地址
		defer resp.Body.Close()
		if err != nil {
			fmt.Fprintf(os.Stderr, "copy file failed:%s: %v\n", url, err)
			os.Exit(1)
		}
		//fmt.Printf("%s", b)
		fmt.Println("write:", n)
		fmt.Println(wt.Size())
		fmt.Println(*os.Stdout)
		wt.Flush()
	}
}
